#include <QDebug>

#include "cvimagehttp.h"
#include "cvsession.h"

CVImageHttp::CVImageHttp(QUrl url)
{
    this->mUrl = url;
    this->defaultImage = new QImage(":/images/user_default");
    init();
}

void CVImageHttp::setDefaultImage(QImage *image)
{
    this->defaultImage = image;
}

void CVImageHttp::readyReadSlot()
{
    // ready read
    //qDebug() << "--CVImageHttp::readyReadSlot--";
    CVImageCache *cache = CVImageCache::instance();
    if (cache->contains(reply->url()))
    {
        reply->abort();
        qDebug() << "Read from cache: " << reply->url();
        QImage image = cache->get(reply->url());
        emit handleImage(QPixmap::fromImage(image));

    }
}

void CVImageHttp::downloadProgressSlot(qint64 bytesReceived, qint64 total)
{
    // do nothing
    //qDebug() << "--CVImageHttp::downloadProgressSlot--";
}

void CVImageHttp::finishedSlot()
{
    // finish request
    qDebug() << "--CVImageHttp::finishedSlot--";
    if (reply->error() == QNetworkReply::NoError)
    {
        if (reply->bytesAvailable() != 0)
        {
            QImageReader *reader = new QImageReader(reply);
            QImage image = reader->read();
            QUrl url = reply->url();
            CVImageCache *cache = CVImageCache::instance();
            cache->add(url, image);

            emit handleImage(QPixmap::fromImage(image));
        }
        else
        {
            qDebug() << "Can not get image: " << reply->url();
            qDebug() << "User Default icon";
            emit handleImage(QPixmap::fromImage(*defaultImage));
        }
    }
    else
    {
        qDebug() << "--CVImageHttp::finishedSlot-- error: " << reply->error();
    }

    reply->deleteLater();
}

void CVImageHttp::errorSlot(QNetworkReply::NetworkError error)
{
    // request error
    qDebug() << "--CVImageHttp::errorSlot--" << error;
    qDebug() << "--CVImageHttp::errorSlot--" << reply->url();
    qDebug() << "==set default icon==";
    emit handleImage(QPixmap::fromImage(*defaultImage));
}

void CVImageHttp::ignoreSslError(QNetworkReply *reply, QList<QSslError> error)
{
    qDebug() << "--CVImageHttp::ignoreSslError--";
    reply->ignoreSslErrors();
}

void CVImageHttp::init()
{
    if (mUrl.isValid())
    {
        //qDebug() << "Read from url: " << mUrl;
        CVSession *session = CVSession::get();
        QList<QNetworkCookie> cookies = session->getCookies();


        manager = new QNetworkAccessManager();
        QNetworkRequest request(mUrl);
        if (!cookies.isEmpty() && !cookies.size() == 0)
        {
            QVariant var;
            var.setValue(cookies);
            request.setHeader(QNetworkRequest::CookieHeader, var);
        }
        else
        {
            qDebug() << "No cookies set for image: "<< mUrl;
        }
        reply = manager->get(request);
        initSlots();
    }
    else
    {
        qDebug() << "Not valid url: " << mUrl;
    }
}

void CVImageHttp::initSlots()
{
    connect(reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgressSlot(qint64,qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorSlot(QNetworkReply::NetworkError)));
    connect(manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(ignoreSslError(QNetworkReply*,QList<QSslError>)));
}

